
package ylg.com.cn.beuty.http;


import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;





import org.apache.http.Header;
import org.apache.http.entity.ByteArrayEntity;
import org.haitao.common.utils.AppLog;
import org.haitao.common.utils.JsonFormatTool;
import org.haitao.common.utils.NetWorkUtil;
import org.haitao.common.utils.ToastUtil;

import java.util.List;

import ylg.com.cn.beuty.config.MyApplication;
import ylg.com.cn.beuty.entity.User;
import ylg.com.cn.beuty.main.MainActivity;
import ylg.com.cn.beuty.utils.Tools;

/**
 * Description http 请求
 * Author by wangHaitao(a758277560@gmail.com)
 * Created  on 2015/12/3
 * Version 1.0
 */
public class HttpUtil {

    /**
     * 请求失败:服务器错误
     */
    public static final int ERROR_SERVER = 500;

    /**
     * 请求失败:URL 无效
     */
    public static final int ERROR_URL = 404;
    /**
     * 请求失败: 请求无法理解
     */
    public static final int ERROR_REQUEST = 400;

    /**
     * 请求失败:服务器没有响应
     */
    public static final int ERROR_RESNPONSE = 0;

    /**
     * 请求失败:服务器请求 返回 false
     */
    public static final int ERROR_FALSE = 222;
    /**
     * 请求失败:服务器请求 返回 不是json
     */
    public static final int ERROR_DATA = 333;
    /**
     * 请求失败:网络不可用
     */
    public static final int ERROR_NETWORK = 444;

    public static AsyncHttpClient client = new AsyncHttpClient();

    private static boolean inHome;

    private static void post(final String url,  RequestParams params, final NetCallBack callback, @SuppressWarnings("rawtypes") final Class type, final boolean isList,String requestJson) {

        // 网络是否可用
        if (checkNet(callback)) {

            if (params == null) {
                params = new RequestParams();
            }
            params.put("deviceType", "1");// android
            User user= MyApplication.getInstance().user;
            if (user!=null) {
                params.put("userToken", user.getToken());
                params.put("phone", user.getUserAccount());
            }
            AppLog.e("url=" + url + "\ndatas= " + params);
            //测试 请求超时 12秒
            client.setTimeout(12000);
            final RequestParams tmepparams=params;

            if (requestJson==null){
                client.post(url, params, new AsyncHttpResponseHandler() {

                    @Override
                    public void onCancel() {
                        super.onCancel();
                        if (callback != null) {
                            callback.onCancel();
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        if (callback != null) {
                            callback.onFinish();
                        }
                    }

                    @Override
                    public void onProgress(int bytesWritten, int totalSize) {
                        super.onProgress(bytesWritten, totalSize);
                        if (callback != null) {
                            callback.onProgress(bytesWritten, totalSize);
                        }
                    }

                    @Override
                    public void onStart() {
                        super.onStart();
                        if (callback != null) {
                            callback.onStart();
                        }
                    }

                    @Override
                    public void onFailure(int error_code, Header[] arg1, byte[] arg2, Throwable arg3) {
                        AppLog.e("post--fail" + "\t" + " url=" + url + "\t" + "error_code=" + error_code+"\t" +"data=" + tmepparams);
                        String error = "其它未知错误!";
                        if (error_code == 0) {
                            AppLog.e("ser not response");
                            error = "连接超时，请稍候重试。";
                        } else if (error_code == 404) {
                            AppLog.e("url not found");
                            //error = "请求地址不存在，请稍候重试。";
                            error = "网络请求失败，请稍候重试。";
                        } else if (error_code == 500) {
                            //error = "服务器出错误了，请稍候重试。";
                            AppLog.e("server error");
                            error = "网络请求失败，请稍候重试。";
                        } else if (error_code == 400) {
                            error = "请求出错了，请稍候重试。";
                            //AppLog.e("server error");
                            error = "网络请求失败，请稍候重试。";
                        } else {
                            //error = "其它未知错误，请稍候重试。";
                            error = "网络请求失败，请稍候重试。";
                        }
                        ToastUtil.shortShowToast(error);
                        if (callback != null) {
                            callback.onFail(false,error_code, "");
                        }
                    }
                    /*result：Boolean	//表示服务器执行成功与否，truer==成功，false==失败
                    code：Integer		//表示执行结果，200==正常执行，400==参数有误……等等……
                    errorMessage：String	//对失败原因的具体说明，例如“XX参数不能为空”
                    response：Map*/
                    @Override
                    public void onSuccess(int arg0, Header[] headers, byte[] responseBt) {
                        formartResult(arg0, headers, responseBt, url, tmepparams, callback, type, isList);
                    }

                });
            }else{
                ByteArrayEntity entity = new ByteArrayEntity(requestJson.getBytes());
                client.post(MyApplication.getInstance(),url, entity, "application/json", new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int arg0, Header[] headers, byte[] responseBt) {
                        formartResult(arg0, headers, responseBt, url, tmepparams, callback, type, isList);
                    }

                    @Override
                    public void onFailure(int error_code, Header[] headers, byte[] bytes, Throwable throwable) {
                        AppLog.e("post--fail" + "\t" + " url=" + url + "\t" + "error_code=" + error_code+"\t" +"data=" + tmepparams);
                        String error = "其它未知错误!";
                        if (error_code == 0) {
                            AppLog.e("ser not response");
                            error = "连接超时，请稍候重试。";
                        } else if (error_code == 404) {
                            AppLog.e("url not found");
                            //error = "请求地址不存在，请稍候重试。";
                            error = "网络请求失败，请稍候重试。";
                        } else if (error_code == 500) {
                            //error = "服务器出错误了，请稍候重试。";
                            AppLog.e("server error");
                            error = "网络请求失败，请稍候重试。";
                        } else if (error_code == 400) {
                            error = "请求出错了，请稍候重试。";
                            //AppLog.e("server error");
                            error = "网络请求失败，请稍候重试。";
                        } else {
                            //error = "其它未知错误，请稍候重试。";
                            error = "网络请求失败，请稍候重试。";
                        }
                        ToastUtil.shortShowToast(error);
                        if (callback != null) {
                            callback.onFail(false,error_code, "");
                        }
                    }
                });

            }

        }
    }

    /**
     * 请求前判断网络
     * @param callback
     * @return
     */
    private static boolean checkNet(final NetCallBack callback){
        if (!NetWorkUtil.isNetworkAvailable(MyApplication.getInstance())) {
            ToastUtil.shortShowToast("当前网络不可用！");
            if (callback != null) {
                callback.onFail(false,ERROR_NETWORK, "当前网络不可用。");
            }
            return false;
        }
        return true;
    }

    /**
     * 请求结果统一解析
     * @param arg0
     * @param headers
     * @param responseBt
     * @param url
     * @param params
     * @param callback
     * @param type
     * @param isList
     */
    @SuppressWarnings("unchecked")
    public  static void formartResult(int arg0, Header[] headers, byte[] responseBt,final String url,  RequestParams params, final NetCallBack callback, @SuppressWarnings("rawtypes") final Class type, final boolean isList){

        String jsonString = new String(responseBt);
        AppLog.e(url+ JsonFormatTool.formatJson(jsonString));
        // 放在这里解析json 数据
        if (callback != null) {
            JSONObject json = null;
            boolean result = false;
            int code = 0;
            String message = null;
            String response = null;
            try {
                json = JSON.parseObject(jsonString);
                result = json.getBoolean("result");
                message = json.getString("errorMessage");
                code =json.getIntValue("code");
                response = json.getString("response");
            } catch (JSONException e) {
                e.printStackTrace();
                ToastUtil.shortShowToast("数据解析错误，请稍候重试");
                if (callback != null) {
                    callback.onFail(true, ERROR_DATA, "");
                }
                // 后面不要执行
                return;
            }
            // 响应成功
            if (code==0) {
                if (type != null) {
                    // json 解析 有数据
                    if (response != null && !"".equals(response) && !"null".equals(response)) {
                        ResultModel body = new ResultModel();
                        try {
                            if (isList) {
                                List<?> ls = JSON.parseArray(response, type);
                                body = new ResultModel();
                                body.setModelList(ls);
                            }else{
                                body.setModel(JSON.parseObject(response, type));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtil.shortShowToast("数据解析错误，请稍候重试");
                            if (callback != null) {
                                callback.onFail(true, ERROR_DATA, "");
                            }
                            return;
                        }
                        // 不该 try 的地方不要try  下面的代码不应该try
                        if (callback != null) {
                            callback.onSuccess(message, body);
                        }

                    } else {
                        // 没有model
                        if (callback != null) {
                            ResultModel  body = new ResultModel();
                            callback.onSuccess(message, body);
                        }
                    }
                } else {
                    // 没有model
                    if (callback != null) {
                        callback.onSuccess(message, null);
                    }
                }

            } else {

                if (51==code || 52==code || 53==code) {
                    // 消失对话框
                    if (callback != null) {
                        callback.onFail(true, code, message);
                    }
                    Tools.dismissWaitDialog();// 很重要！！！！
                    //
                    String runningActivity = null;
                    try {
                        ActivityManager am = (ActivityManager) MyApplication.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
                        runningActivity=am.getRunningTasks(1).get(0).topActivity.getClassName();
                    } catch (Exception e) {

                    }
                    if (!"net.neiquan.yida.activity.LoginActivity".equals(runningActivity) && !inHome) {
                        inHome=true;
                        Tools.dismissWaitDialog();
                        Intent intent = new Intent(MyApplication.getInstance(), MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.putExtra("sessionOut", true);
                        MyApplication.getInstance().startActivity(intent);
                    }

                }else{
                    if (callback != null) {
                        callback.onFail(true, code, message);
                    }
                }

            }

        }

    }

    public static void post(String url, RequestParams params, final NetCallBack callback, final Class type) {
        post(url, params, callback, type, false,null);
    }

    public static void postList(String url, RequestParams params, final NetCallBack callback, final Class type) {
        post(url, params, callback, type, true,null);
    }
    public static void postBodyList(String url, String json, final NetCallBack callback, final Class type) {
        post(url, null, callback, type, true,json);
    }
    public static void postBody(String url, String json, final NetCallBack callback, final Class type) {
        post(url, null, callback, type, false,json);
    }

}

